# coding=utf-8

from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_mail import Mail
from flask_wtf import CSRFProtect
from flask_bootstrap import Bootstrap
from flask_socketio import SocketIO

from app.cores.session_id_manager import SessionIDManager
from app.cores.dispatcher_scheduler import DispatcherScheduler


db = SQLAlchemy()
# render_as_batch=True在修改sqlite表结构后进行flask db migrate/upgrade升级时自动进行copy-and-move
migrate = Migrate(render_as_batch=True)
login_manager = LoginManager()
login_manager.login_view = "auth.login"  # 注册登录视图
login_manager.login_message_category = 'warning'
login_manager.login_message = "请先登录"
mail = Mail()
csrf = CSRFProtect()
bootstrap = Bootstrap()
# 支持后台线程发送，并被前端接收到
# async_mode = 'threading'
async_mode = 'eventlet'
if async_mode == 'eventlet':
    import eventlet
    eventlet.monkey_patch()
elif async_mode == 'gevent':
    from gevent import monkey
    monkey.patch_all()
socketio = SocketIO(async_mode=async_mode)
session_id_manager = SessionIDManager()
dispatcher_scheduler = DispatcherScheduler()


@login_manager.user_loader
def load_user(id):
    from app.models import User
    return User.query.filter_by(id=int(id)).first()

# 注册websocket事件
